//
//  ZPSelectClassVC.m
//  ZPIOSEducation
//
//  Created by mini1 on 2017/1/16.
//  Copyright © 2017年 mini1. All rights reserved.
//

#import "ZPSelectClassVC.h"
#import "ZPSelectTiaoClassCell.h"
#import "ZPStateAllViewController.h"
#import "ZPMineClassViewController.h"
#import "ZPTeacherDetailViewController.h"
#import "SHaiXuanViewController.h"
#import "ZPMineClassChangeRecordVC.h"

static NSString  * const reuseIdentifier = @"ZPSelectCurriculumCell";

@interface ZPSelectClassVC ()<UITableViewDelegate,UITableViewDataSource>{
    UIBarButtonItem *btn;
    __weak IBOutlet UIView *topView;
}
@property (copy,nonatomic) NSString *teacherId;
@property (copy,nonatomic) NSString *teachId;
@property (weak, nonatomic) IBOutlet UILabel *toptitle;
@property (weak, nonatomic) IBOutlet UITableView *selectClassTabV;
@property (weak, nonatomic) IBOutlet UIButton *completeBtn;
@property (strong, nonatomic) ZPSelectTiaoClassCell *classCell;
@property (strong,nonatomic) NSArray *arr;
@property (weak, nonatomic) IBOutlet UIView *emptyView;

@property (strong,nonatomic) NSMutableDictionary *paramDic;
@end

@implementation ZPSelectClassVC

- (ZPSelectTiaoClassCell *)classCell
{
    if (_classCell == nil) {
        _classCell = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([ZPSelectTiaoClassCell class]) owner:self options:nil] lastObject];
    }
    return _classCell;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    _paramDic =[NSMutableDictionary dictionary];
    [_paramDic setObject:_classId forKey:@"oldClassId"];
    [_paramDic setObject:[[[ZPAuthStore sharedZPAuthStore] userToDic] objectForKey:@"stuId"] forKey:@"stuId"];
    hud = [[MBProgressHUD alloc]initWithView:self.view];
    [self.view addSubview:hud];
    self.selectClassTabV.delegate = self;
    self.selectClassTabV.dataSource = self;
    [_selectClassTabV registerNib:[UINib nibWithNibName:@"ZPSelectTiaoClassCell" bundle:nil] forCellReuseIdentifier:reuseIdentifier];
    
    btn = [[UIBarButtonItem alloc]initWithTitle:@"筛选" style:UIBarButtonItemStylePlain target:self action:@selector(toShaiXuan)];
    [self.navigationItem setRightBarButtonItem:btn];
    if (self.chooseListStr) {
        _toptitle.text=@"请选择要调入的班级：";
        [_completeBtn setTitle:@"调入" forState:UIControlStateNormal];
    }else{
        _toptitle.text=@"请选择要转入的班级：";
        [_completeBtn setTitle:@"转入" forState:UIControlStateNormal];
    }
    
    [self getintoclasslist];
}

-(void)toShaiXuan{
    SHaiXuanViewController *vc=[[SHaiXuanViewController alloc]init];
    vc.classId = _classId;
    vc.paramDic = [NSMutableDictionary dictionary];
    if ([_paramDic.allKeys containsObject:@"teacherId"]) {
        [vc.paramDic setObject:toStr([_paramDic objectForKey:@"teacherId"]) forKey:@"teacherId"];
    }
    if ([_paramDic.allKeys containsObject:@"teachId"]) {
        [vc.paramDic setObject:toStr([_paramDic objectForKey:@"teachId"]) forKey:@"teachId"];
    }
    __weak typeof(self) weak = self;
    vc.resetBlock=^(NSArray *arr){
        _teachId=@"";
        _teacherId=@"";
        [_paramDic removeObjectsForKeys:arr];
        [weak getintoclasslist];
    };
    vc.confirmBlock=^(NSDictionary *dic){
        [weak.paramDic addEntriesFromDictionary:dic];
        
        if ([dic.allKeys containsObject:@"teacherId"]) {
            _teacherId = toStr([dic objectForKey:@"teacherId"]);
        }
        if ([dic.allKeys containsObject:@"teachId"]) {
            _teachId = toStr([dic objectForKey:@"teachId"]);
        }
        [_paramDic addEntriesFromDictionary:dic];
        [weak getintoclasslist];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)getintoclasslist{
    [hud showAnimated:YES];
    
    NSString *url;
    if (self.chooseListStr) {
        url=@"adjust/getscheintoclasslist.json";
    }else{
        url=@"adjust/getintoclasslist.json";
    }
    
    
    [[ZPNetworking sharedZPNetworking] POST:[NSString stringWithFormat:@"%@%@",APIUC,url] parameters:@{@"stuId":[[[ZPAuthStore sharedZPAuthStore] userToDic] objectForKey:@"stuId"],@"classId":_classId,@"teacherId":toStr(_teacherId),@"teachId":toStr(_teachId)} progress:nil success:^(id  _Nonnull responseObject) {
        [hud hideAnimated:YES];
        if (CodeIs200(responseObject)) {
            _arr = [responseObject objectForKey:@"result"];
            
            if (_arr.count==0) {
                _selectClassTabV.hidden=YES;
                _emptyView.hidden=NO;
                topView.hidden=_completeBtn.hidden=YES;
            }else{
                _selectClassTabV.hidden=NO;
                _emptyView.hidden=YES;
                topView.hidden=_completeBtn.hidden=NO;
            }
            [_selectClassTabV reloadData];
            [_paramDic removeObjectForKey:@"newClassId"];
            _completeBtn.enabled=NO;
            [_completeBtn setBackgroundColor:UIColorFromRGB(0x999999)];
        }else{
            [ZPPromptView showMessage:toStr([responseObject objectForKey:@"codeMsg"])];
        }
    } failure:^(NSError * _Nonnull error) {
        [ZPPromptView showMessage:error.localizedDescription];
        [hud hideAnimated:YES];
    }];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.title = @"选择班级";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"zhenpin_back"] style:UIBarButtonItemStylePlain target:self action:@selector(backButtonClick)];
}

- (void)backButtonClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *tmp = [_arr objectAtIndex:indexPath.row];
    NSString *str =toStr([tmp objectForKey:@"className"]);
    float h = ceilf([str calculateSize:CGSizeMake(SCREENWIDTH-142, 9999) font:[UIFont systemFontOfSize:14]].height)+108;
    return h;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *tmp = [_arr objectAtIndex:indexPath.row];
    ZPSelectTiaoClassCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    cell.className.text=toStr([tmp objectForKey:@"className"]);
    cell.curriculumDate.text=toStr([tmp objectForKey:@"time"]);
    cell.address.text=toStr([tmp objectForKey:@"teachName"]);
    cell.teacher.text=toStr([tmp objectForKey:@"teacherName"]);
    cell.teacherId=toStr([tmp objectForKey:@"teacherId"]);
    [cell.teacherImgV sd_setImageWithURL:[tmp objectForKey:@"headUrl"] placeholderImage:Z_IMAGE(@"headportrait")];
    __weak typeof(self) weak = self;
    cell.detailBlock=^(NSString *teacherId){
        [weak toDetail:teacherId];
    };
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [_paramDic setObject:[[_arr objectAtIndex:indexPath.row] objectForKey:@"classId"] forKey:@"newClassId"];
    _completeBtn.enabled = YES;
    [_completeBtn setBackgroundColor:UIColorFromRGB(0x21A4EB)];
}

-(void)toDetail:(NSString *)teacherId{
    ZPTeacherDetailViewController *vc=[[ZPTeacherDetailViewController alloc]init];
    vc.teacherId = teacherId;
    [self.navigationController pushViewController:vc animated:YES];
}


- (IBAction)completeBtnClick:(id)sender
{

    
    if (self.chooseListStr) {
        [self  showHudithString:@"发送中..."];
        
        NSDictionary  *paramDic = [NSDictionary  dictionaryWithObjectsAndKeys:
                                   [[ZPAuthStore  sharedZPAuthStore].userToDic  objectForKey:@"stuId"],@"stuId",
                                   [NSString  stringWithFormat:@"%@",[_paramDic objectForKey:@"newClassId"]],@"newClassId",
                                   [NSString  stringWithFormat:@"%@",self.chooseListStr],@"chooseList",
                                   nil];
        [[ZPNetworking  sharedZPNetworking] POST:APIUC@"adjust/scheduleadjust.json" parameters:paramDic progress:^(NSProgress * _Nullable progress) {
            
        } success:^(id  _Nonnull responseObject) {
            NSLog(@"======%@",responseObject);
            [self  hiddenHud];
            
            if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
                if ([[[responseObject  objectForKey:@"result"] objectForKey:@"isOk"] boolValue]) {
                    ZPMineClassChangeRecordVC  *viewController = [[ZPMineClassChangeRecordVC  alloc] init];
                    viewController.needPopToRoot = YES;
                    [self.navigationController  pushViewController:viewController animated:YES];
                    
                }else {
                    [ZPPromptView  showMessage:@"调课失败"];
                }
            }else {
                [ZPPromptView  showMessage:[responseObject  objectForKey:@"codeMsg"]];
            }
            
        } failure:^(NSError * _Nonnull error) {
            [self  hiddenHud];
            
        }];
        
        
    }else {
        [hud showAnimated:YES];
        [[ZPNetworking sharedZPNetworking] POST:APIUC@"adjust/classadjust.json" parameters:_paramDic progress:nil success:^(id  _Nonnull responseObject) {
            [hud hideAnimated:YES];
            if (CodeIs200(responseObject)) {
                NSDictionary *result = [responseObject objectForKey:@"result"];
                
                if ([[result objectForKey:@"isOk"] boolValue]) {
                    ZPMineClassChangeRecordVC  *viewController = [[ZPMineClassChangeRecordVC  alloc] init];
                    viewController.needPopToRoot = YES;
                    [self.navigationController  pushViewController:viewController animated:YES];
                }else{
                    [ZPPromptView showMessage:toStr([result objectForKey:@"msg"])];
                }
                
                
                
            }else{
                [ZPPromptView showMessage:toStr([responseObject objectForKey:@"codeMsg"])];
            }
        } failure:^(NSError * _Nonnull error) {
            [ZPPromptView showMessage:error.localizedDescription];
            [hud hideAnimated:YES];
        }];
    }
    
    
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
